package com.edu.koTA07.takingOrder;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SlidingDrawer;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;

import com.edu.koTA07.adapter.BarangPesananCheckboxListAdapter;
import com.edu.koTA07.adapter.PesananListAdapter;
import com.edu.koTA07.bean.BarangBean;
import com.edu.koTA07.bean.KategoriBarangBean;
import com.edu.koTA07.bean.PesananDetailBean;
import com.edu.koTA07.utils.BarangUtils;
import com.edu.koTA07.utils.KategoriBarangUtils;
import com.edu.koTA07.utils.PesananDetailUtils;

public class AddPesanan extends ListActivity implements OnDrawerOpenListener,
OnDrawerCloseListener {	
	private ListView listView;
	private ListView listViewBarangYangDipesan;
	PesananListAdapter pesananListAdapter;
	private List<BarangBean> currentData;//baca semua barang
	private ArrayList<BarangBean> barangSortedByKategori;//barang tersort berdasarkan kategori
	private ArrayList<PesananDetailBean> pesananCurrent;// pesanan yang dipesan
	private ArrayList<KategoriBarangBean> getDataKategori;// ambil data kategori
	BarangBean barangBean;
	BarangUtils util;
	KategoriBarangUtils kategoriBarangUtil;
	PesananDetailUtils pesananDetailUtil;
	private SlidingDrawer slidingDrawer;
	BarangPesananCheckboxListAdapter barangPesananCheckboxListAdapter;
	String iDPesanan;
	Spinner spinner;
	String newIdChecked;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_pesanan);
		currentData = new ArrayList<BarangBean>();
		pesananCurrent = new ArrayList<PesananDetailBean>();
		util = new BarangUtils(this);

        currentData = util.loadData();
		kategoriBarangUtil = new KategoriBarangUtils(this);
        
		Button button = (Button) findViewById(R.id.backToMainButton);		
		button.setOnClickListener(new OnClickListener() {
	
			public void onClick(View v) {					
				
				Toast.makeText(AddPesanan.this,
						"Please wait...", Toast.LENGTH_SHORT)
						.show();
				
	     		Intent Intent = new Intent(AddPesanan.this,
						Main.class);
				startActivity(Intent);
				finish();
			}
		});
		pesananDetailUtil = new PesananDetailUtils(this);
		Button buttonSave = (Button) findViewById(R.id.updateBarangPesanan);		
		buttonSave.setOnClickListener(new OnClickListener() {
	
			public void onClick(View v) {					
				
				Toast.makeText(AddPesanan.this,
						"Please wait...", Toast.LENGTH_SHORT)
						.show();
				pesananDetailUtil.onSaveData(pesananListAdapter.getItemAll());
				new XmlFileCreatorPesanan(pesananListAdapter.getItemAll());
	     		Intent Intent = new Intent(AddPesanan.this,
						Main.class);
				startActivity(Intent);
				finish();
			}
		});
	    
		spinnerKategori();
		/*Button buttonchecked = (Button) findViewById(R.id.viewCheckedItemsButton);		
		buttonchecked.setOnClickListener(new OnClickListener() {
	
			public void onClick(View v) {					
				
				showSelectedItems();
			}
		});*/
		slidingDrawer = (SlidingDrawer) this.findViewById(R.id.slidingDrawerListBarangDipesan);
		slidingDrawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {
			
			public void onDrawerOpened() {
				// TODO Auto-generated method stub
				
			}
		});
		slidingDrawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {
			
			public void onDrawerClosed() {
				// TODO Auto-generated method stub
				for(int j=0; j<barangSortedByKategori.size(); j++){
					
					
					listView.setItemChecked(j, barangSortedByKategori.get(j).isSelected());
				}
			}
		});
	}
	
	
	/**
	 * Called when the user presses one of the buttons in the main view
	 */
	/*public void onButtonClick(View v) {
		if (v.getId()==R.id.viewCheckedItemsButton)
			showSelectedItems();
		
	}*/
	@SuppressWarnings("unchecked")
	private void spinnerKategori() {
		getDataKategori = new ArrayList<KategoriBarangBean>();
	    getDataKategori = kategoriBarangUtil.loadData();
	    String [] ret = new String[getDataKategori.size()];
		for(int i = 0;i<getDataKategori.size();i++){
			//ret[i][0] = getDataKategori.get(i).getNamaKategoriBarang();
			ret[i] = getDataKategori.get(i).getNamaKategoriBarang();
		}
		
		spinner = (Spinner) findViewById(R.id.kategoriBarangSpinner);
	    ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this,
	   		android.R.layout.simple_spinner_item, ret);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner.setAdapter(adapter);
	    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(
					 AdapterView adapterView,
					View view, int i, long l) {
					String idKategoriBarang = getDataKategori.get(spinner.getSelectedItemPosition()).getIDKategoriBarang();
					updateListBarang(idKategoriBarang);
			}
	
			public void onNothingSelected(
					AdapterView adapterView) {
				return;
			}
		});
	}
	
	
	public void updateListBarang(String idKategoriBarang){
		
		barangSortedByKategori = new ArrayList<BarangBean>();
        for(int i=0; i<currentData.size(); i++){
        	if(idKategoriBarang.equals(currentData.get(i).getIDKategori())){
        		barangSortedByKategori.add(currentData.get(i));
        		Log.d("ischecked", ""+currentData.get(i).isSelected());
        	}
        }
        // Create the adapter to render our data
		// --
        barangPesananCheckboxListAdapter = new BarangPesananCheckboxListAdapter(this, barangSortedByKategori);
        setListAdapter(barangPesananCheckboxListAdapter);
        //barangPesananCheckboxListAdapter.forceReload();
		// Get some views for later use
		// --
    	listView = getListView();
		listView.setItemsCanFocus(false);
	
		for(int j=0; j<barangSortedByKategori.size(); j++){
			
			
			listView.setItemChecked(j, barangSortedByKategori.get(j).isSelected());
		}
		
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				
					//if(!barangSortedByKategori.get(position).isSelected()){
				// TODO Auto-generated method stub
						selectedItems(barangSortedByKategori.get(position).getIDBarang());
					//}
					
			}
		});
		
		
		
		//clearSelection();
	}
	
	/**
	 * Show a message giving the selected item captions
	 */
	private void selectedItems(String idCheckedBarang) {
		//final StringBuffer sb = new StringBuffer("Selection: ");

		// Get an array that tells us for each position whether the item is
		// checked or not
		// --
		
		
		
		final SparseBooleanArray checkedItems = listView
				.getCheckedItemPositions();
		if (checkedItems == null) {
			Toast.makeText(this, "No selection",
					Toast.LENGTH_LONG).show();
			return;
		}

		// For each element in the status array
		// --
		//boolean isFirstSelected = true;
		final int checkedItemsCount = checkedItems.size();
		//PesananDetailBean pD = new PesananDetailBean();
		Bundle extras = getIntent().getExtras();
		if(extras != null){
			iDPesanan = extras.getString("id_pesanan");
		}
		for (int i = 0; i < checkedItemsCount; ++i) {
			// This tells us the item position we are looking at
			// --
			final int position = checkedItems.keyAt(i);

			// This tells us the item status at the above position
			// --
			final boolean isChecked = checkedItems.valueAt(i);
			for(int j=0; j<currentData.size(); j++){
	        	//if(){
	        		
	        	//}
	        	if (barangSortedByKategori.get(position).getIDBarang().equals(currentData.get(j).getIDBarang())) {
	        		if (isChecked){ 	
	        			barangSortedByKategori.get(position).setSelectedBarang(true);
		        		currentData.get(j).setSelectedBarang(true);
						PesananDetailBean pD = new PesananDetailBean();
						pD.setIDBarang(barangSortedByKategori.get(position).getIDBarang());
						pD.setIDPesanan(iDPesanan);
						//
						//pD.setKuantitasPesanan();
						if(barangSortedByKategori.get(position).getIDBarang().equals(idCheckedBarang)) {
							pesananCurrent.add(pD);
						}
						//sb.append(b.getNamaBarang());
						//isFirstSelected = false;
	        		}
	        		else {
	        			//if(barangSortedByKategori.get(position).isSelected()){
	        			for(int k=0; k<pesananCurrent.size(); k++){
	        				if(pesananCurrent.get(k).getIDBarang().equals(currentData.get(j).getIDBarang())){
	        					pesananCurrent.remove(k);
	        				}
	        			}
	        			currentData.get(j).setSelectedBarang(false);
	        			
	        			barangSortedByKategori.get(position).setSelectedBarang(false);
	        			//}//pesananCurrent.remove(object);
	        		}
				}
				else
				{
					//if(!isChecked){
					//barangSortedByKategori.get(position).setSelectedBarang(false);
					//currentData.get(j).setSelectedBarang(false);
					//}
				}
	        }
				
		}
		listViewBarangYangDipesan = (ListView) findViewById(R.id.list_barang_yang_akan_dipesan);
        pesananListAdapter = new PesananListAdapter(this, pesananCurrent, currentData);
        listViewBarangYangDipesan.setAdapter(pesananListAdapter);
        currentData = pesananListAdapter.getCurrentDataBack();
        
        //clearSelection() ;
	}

	/**
	 * Uncheck all the items
	 */	
	@SuppressWarnings("unused")
	private void clearSelection() {
		final SparseBooleanArray checkedItems = listView
		.getCheckedItemPositions();
		final int checkedItemsCount = checkedItems.size();
		for (int i = 0; i < checkedItemsCount; ++i) {
			// This tells us the item position we are looking at
			// --
			final int position = checkedItems.keyAt(i);
			for(int j=0; j<currentData.size(); j++){
				if (barangSortedByKategori.get(position).getIDBarang().equals(currentData.get(j).getIDBarang())) {
					listView.setItemChecked(position, currentData.get(j).isSelected());
				}
			}
		}
		barangPesananCheckboxListAdapter.forceReload();
	}

	public void onDrawerOpened() {
		listView.setVisibility(View.GONE);
	}

	public void onDrawerClosed() {
		listView.setVisibility(View.VISIBLE);
	}
}   